//
//  YWHttpTool.m
//  通信录
//
//  Created by yellow on 16/7/12.
//  Copyright © 2016年 yellow. All rights reserved.
//
#import "YWHttpTool.h"

#import "YWUploadParam.h"

@implementation YWHttpTool


+(AFHTTPSessionManager *)manager
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 超时时间
    manager.requestSerializer.timeoutInterval = 60;
    
    // 声明上传的是json格式的参数，需要你和后台约定好，不然会出现后台无法获取到你上传的参数问题
    manager.requestSerializer = [AFHTTPRequestSerializer serializer]; // 上传普通格式
    // manager.requestSerializer = [AFJSONRequestSerializer serializer]; // 上传JSON格式
    
    // 声明获取到的数据格式
    manager.responseSerializer = [AFHTTPResponseSerializer serializer]; // AFN不会解析,数据是data，需要自己解析
    // manager.responseSerializer = [AFJSONResponseSerializer serializer]; // AFN会JSON解析返回的数据
    // 个人建议还是自己解析的比较好，有时接口返回的数据不合格会报3840错误，大致是AFN无法解析返回来的数据
    
    
    //接受类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/plain",@"text/javascript", nil];
    
    return manager;
}



+ (void)GET:(NSString *)URLString parameters:(id)parameters success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    // 创建请求管理者
    AFHTTPSessionManager *manager = [self manager];
    
    [manager GET:URLString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        // 这里可以获取到目前数据请求的进度
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
        // 请求成功
        NSError *error = nil;
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
        
        if (success) {
            success(dic);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        // 请求失败
        YWLog(@"提交失败：%@",error);
        
        if (failure) {
            failure(error);
        }
        
    }];
    
    
}


+ (void)Get:(NSString *)URLString
 parameters:(id)parameters
    success:(void (^)(id responseObject))success
    failure:(void (^)(NSError *error))failure{
    // 创建请求管理者
      AFHTTPSessionManager *manager = [self manager];
       //设置请求头
          NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
          
          NSString *access_token = [defaults objectForKey:accessTokenStr];
          NSString *token_type = [defaults objectForKey:tokenTypeStr];
          
          NSString *totalToken = [NSString stringWithFormat:@"%@ %@",token_type,access_token];
          
          [manager.requestSerializer setValue:totalToken forHTTPHeaderField:@"Authorization"];
          
          //添加了这两句（这是由自己的后台配合决定的，有的后台要加有的后台不需要加）
      //    manager.requestSerializer = [AFJSONRequestSerializer serializer]; // 上传JSON格式
          
          //不需要这句，因为后面返回data我自己把它转为NSDictionary
      //    manager.responseSerializer = [AFJSONResponseSerializer serializer];
          
      [manager GET:URLString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
          // 这里可以获取到目前数据请求的进度
          
          
      } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
          // 请求成功
          NSError *error = nil;
          
          NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
          
          if (success) {
              success(dic);
          }
      } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
          
          // 请求失败
          YWLog(@"提交失败：%@",error);
          
          if (failure) {
              failure(error);
          }
          
      }];
      
    
    
}



+ (void)POST:(NSString *)URLString parameters:(id)parameters success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    
    
    // 创建请求管理者
    AFHTTPSessionManager *manager = [self manager];
    
    
    //添加了这两句（这是由自己的后台配合决定的，有的后台要加有的后台不需要加）
    manager.requestSerializer = [AFJSONRequestSerializer serializer]; // 上传JSON格式
    
    //不需要这句，因为后面返回data我自己把它转为NSDictionary
//    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [manager POST:URLString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        // 这里可以获取到目前数据请求的进度
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
        // 请求成功
        NSError *error = nil;
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
        
//        YWLog(@"%@",dic);
        if ([dic isKindOfClass:[NSDictionary class]]) {
            
//            YWLog(@"%@",dic);
//
//            YWLog(@"%@",dic[@"msg"]);
        }
        
        if (success) {
            success(dic);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 请求失败
        YWLog(@"提交失败：%@",error);
        
        if (failure) {
            failure(error);
        }
    }];
    
    
}



+ (void)SortPost:(NSString *)URLString parameters:(id)parameters success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    
    
    // 创建请求管理者
    AFHTTPSessionManager *manager = [self manager];
    
    //设置请求头
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    
    NSString *access_token = [defaults objectForKey:accessTokenStr];
    NSString *token_type = [defaults objectForKey:tokenTypeStr];
    
    NSString *totalToken = [NSString stringWithFormat:@"%@ %@",token_type,access_token];
    
    [manager.requestSerializer setValue:totalToken forHTTPHeaderField:@"Authorization"];
    
    //添加了这两句（这是由自己的后台配合决定的，有的后台要加有的后台不需要加）
    manager.requestSerializer = [AFJSONRequestSerializer serializer]; // 上传JSON格式
    
    //不需要这句，因为后面返回data我自己把它转为NSDictionary
//    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [manager POST:URLString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        // 这里可以获取到目前数据请求的进度
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
        // 请求成功
        NSError *error = nil;
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
        
//        YWLog(@"%@",dic);
        if ([dic isKindOfClass:[NSDictionary class]]) {
            
//            YWLog(@"%@",dic);
//
//            YWLog(@"%@",dic[@"msg"]);
        }
        
        if (success) {
            success(dic);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 请求失败
        YWLog(@"提交失败：%@",error);
        
        if (failure) {
            failure(error);
        }
    }];
    
    
}

+ (void)Post:(NSString *)URLString parameters:(id)parameters success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    
    
    // 创建请求管理者
    AFHTTPSessionManager *manager = [self manager];
    
    //设置请求头
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
    
    NSString *access_token = [defaults objectForKey:accessTokenStr];
    NSString *token_type = [defaults objectForKey:tokenTypeStr];
    
    NSString *totalToken = [NSString stringWithFormat:@"%@ %@",token_type,access_token];
    
    [manager.requestSerializer setValue:totalToken forHTTPHeaderField:@"Authorization"];
    
    //添加了这两句（这是由自己的后台配合决定的，有的后台要加有的后台不需要加）
//    manager.requestSerializer = [AFJSONRequestSerializer serializer]; // 上传JSON格式
    
    //不需要这句，因为后面返回data我自己把它转为NSDictionary
//    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [manager POST:URLString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        // 这里可以获取到目前数据请求的进度
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
        // 请求成功
        NSError *error = nil;
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
        
//        YWLog(@"%@",dic);
        if ([dic isKindOfClass:[NSDictionary class]]) {
            
//            YWLog(@"%@",dic);
//    
//            YWLog(@"%@",dic[@"msg"]);
        }
        
        if (success) {
            success(dic);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 请求失败
        YWLog(@"提交失败：%@",error);
        
        if (failure) {
            failure(error);
        }
    }];
    
    
}







+ (void)Upload:(NSString *)URLString parameters:(id)parameters uploadParam:(YWUploadParam *)uploadParam success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    
    // 创建管理者对象
    AFHTTPSessionManager *manager = [self manager];
//    [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];

    //设置请求头
//    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
//    
//    NSString *access_token = [defaults objectForKey:accessTokenStr];
//    NSString *token_type = [defaults objectForKey:tokenTypeStr];
//    
//    NSString *totalToken = [NSString stringWithFormat:@"%@ %@",token_type,access_token];
//    
//    [manager.requestSerializer setValue:totalToken forHTTPHeaderField:@"Authorization"];
    
    //添加了这两句（这是由自己的后台配合决定的，有的后台要加有的后台不需要加）
//    manager.requestSerializer = [AFJSONRequestSerializer serializer]; // 上传JSON格式
    
    
    
    //不需要这句，因为后面返回data我自己把它转为NSDictionary
//        manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
        
        // 拼接数据到请求题中
        [formData appendPartWithFileData:uploadParam.data name:uploadParam.name fileName:uploadParam.fileName mimeType:uploadParam.mimeType];
        
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        // 打印上传进度
        NSLog(@"%lf",1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
        //请求成功
        NSError *error = nil;
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
        
        if (success) {
            success(dic);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //请求失败
        if (failure) {
            failure(error);
        }
    }];
    
}

+ (void)Upload2:(NSString *)URLString parameters:(id)parameters uploadParam:(YWUploadParam *)uploadParam success:(void (^)(id))success failure:(void (^)(NSError *))failure
{
    
    // 创建管理者对象
    AFHTTPSessionManager *manager = [self manager];
//    [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"];

    //设置请求头
    NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];

    NSString *access_token = [defaults objectForKey:accessTokenStr];
    NSString *token_type = [defaults objectForKey:tokenTypeStr];

    NSString *totalToken = [NSString stringWithFormat:@"%@ %@",token_type,access_token];

    [manager.requestSerializer setValue:totalToken forHTTPHeaderField:@"Authorization"];
    
    //添加了这两句（这是由自己的后台配合决定的，有的后台要加有的后台不需要加）
//    manager.requestSerializer = [AFJSONRequestSerializer serializer]; // 上传JSON格式
    
    //不需要这句，因为后面返回data我自己把它转为NSDictionary
//        manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
        
        // 拼接数据到请求题中
        [formData appendPartWithFileData:uploadParam.data name:uploadParam.name fileName:uploadParam.fileName mimeType:uploadParam.mimeType];
        
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        // 打印上传进度
        NSLog(@"%lf",1.0 *uploadProgress.completedUnitCount / uploadProgress.totalUnitCount);
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
        //请求成功
        NSError *error = nil;
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
        
        if (success) {
            success(dic);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //请求失败
        if (failure) {
            failure(error);
        }
    }];
    
}


+ (void)Post:(NSString *)URLString
  parameters:(id)parameters time:(CGFloat)time
     success:(void (^)(id responseObject))success
     failure:(void (^)(NSError *error))failure{

    // 创建请求管理者
    AFHTTPSessionManager *manager = [self manager];
    
    // 声明上传的是json格式的参数，需要你和后台约定好，不然会出现后台无法获取到你上传的参数问题
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    // 声明获取到的数据格式
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //设置超时时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    
    manager.requestSerializer.timeoutInterval = time;
    
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    [manager POST:URLString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        // 这里可以获取到目前数据请求的进度
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
        // 请求成功
        NSError *error = nil;
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
        
        if (success) {
            success(dic);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 请求失败
        YWLog(@"提交失败：%@",error);
        
        if (failure) {
            failure(error);
        }
    }];
    



}



@end
